package part1.api.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 集合的排序----Point对象
 */
public class SortPoint {
    public static void main(String[] args) {
        List<Point> list = new ArrayList<>();
        list.add(new Point(1,3));
        list.add(new Point(55,6));
        list.add(new Point(23,98));
        list.add(new Point(5,34));
        list.add(new Point(90,67));
        list.add(new Point(34,2));
        System.out.println("list原始数据："+list);
        Collections.sort(list, new Comparator<Point>() {
            @Override
            public int compare(Point o1, Point o2) {
                int len1 = o1.getX()*o1.getX() +o1.getY()*o1.getY();
                int len2 = o2.getX()*o2.getX() +o2.getY()*o2.getY();
                return len1-len2; //升序
                //return len2-len1; //降序

                //return o1.getX() - o2.getX(); //按x坐标升序
            }
        });

        //Lambda表达式写法
        Collections.sort(list,(o1, o2) -> {
            int len1 = o1.getX()*o1.getX() +o1.getY()*o1.getY();
            int len2 = o2.getX()*o2.getX() +o2.getY()*o2.getY();
            return len1-len2; //升序
        });


        System.out.println("list排序后数据:"+list);

        //jdk1.8时，List集合自身提供了sort方法进行排序，方法中需要传入比较器
        list.sort(new Comparator<Point>() {
            @Override
            public int compare(Point o1, Point o2) {
                return o1.getX()-o2.getX();
            }
        });
        list.sort((o1, o2) -> o1.getX()-o2.getX());
        System.out.println("list排序后数据:"+list);



        List<Student> list1 = new ArrayList<>();
        list1.add(new Student("bob",23));
        list1.add(new Student("ani",23));
        list1.add(new Student("pete",56));
        System.out.println(list1);

        Collections.sort(list1, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int tmp = o1.getAge() - o2.getAge();
                return tmp == 0 ? o1.getName().compareTo(o2.getName()) : tmp;
            }
        });
        System.out.println(list1);


    }
}


class Student{
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}